package de.rj.urwalking.data.survey;

import java.util.Collections;

import android.content.Context;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import de.rj.urwalking.R;
import de.rj.urwalking.config.Config;
import de.rj.urwalking.config.Constants;

/**
 * 
 * This {@link Question} type is used for all questions that consist of a vertical RadioGroup like for example Yes/No
 * questions, .
 * 
 * @author rjj
 * 
 */

public class VerticalRadioQuestion extends Question implements OnCheckedChangeListener {

	private static final long serialVersionUID = 1L;
	private transient RadioGroup radioGroup;

	public VerticalRadioQuestion(int id, int itemNumber, String text, int scaleId, int screen) {
		super(id, itemNumber, text, scaleId, screen);

		// FIXME: nasty hack to sort the scalepoints to make more sense ("Ja" before "Nein")
		if (scaleId == Config.SCALE_YESNO2 || scaleId == Config.SCALE_YESNO || scaleId == Config.SCALE_AGREEMENT) {
			Collections.reverse(scalePoints);
		}

	}

	@Override
	public View buildView(Context context, ViewGroup parent) {
		// load UI from xml layout
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.question_radiogroup_vertical, parent, false);

		setQuestionText(view);
		setupRadioGroup(context, view);
		restoreState();

		return view;
	}

	private void setupRadioGroup(Context context, View view) {
		radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);

		// add scale points from database
		for (ScalePoint scalePoint : scalePoints) {
			RadioButton radioButton = new RadioButton(context);
			radioButton.setText(scalePoint.getTitle());
			radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
			radioButton.setTag(scalePoint.getIntValue());
			radioGroup.addView(radioButton);
		}
		radioGroup.setOnCheckedChangeListener(this);
	}

	private void restoreState() {
		int answerId = getAnswer().getIntAnswer();

		if (answerId == Constants.UNDEFINED) {
			radioGroup.clearCheck();
		} else {
			int id = radioGroup.findViewWithTag(answerId).getId();
			radioGroup.check(id);
		}
	}

	@Override
	public boolean hasBeenAnswered() {
		// A YesNoQuestion is considered as answered if the rating has changed from the initial "undefined" state.
		return getAnswer().getIntAnswer() != Constants.UNDEFINED;

	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		// -1 is used by the system to clear all checks
		if (checkedId == -1) return;

		// save the answer according to the checked RadioButton
		View v = radioGroup.findViewById(checkedId);
		int intAnswer = (Integer) v.getTag();
		updateAnswer(intAnswer);

	}

}
